package data;

import data.obj.Repair;
import jxl.read.biff.BiffException;
import mat.xls.ExcelParser;
import mat.xls.Mat;
import obj.Headset;
import util.Helper;

import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DataGenerator {
    public static int count = 0;
    public static int record_count = 0;
    public static int file_count = 0;
    private static final double COEF = 1.5;
    public static String header;

    public static final Pattern p = Pattern.compile("\\([^)]+");
    private static final String CARS_DATA_FILE = "data/cars/cars.xls";
    private static final String DATA_IMPORT_PATH = "data/import/%s-price.txt";
    private static final String DATA_PATH = "data/%s";
    private static final String PROPERTIES_PATH = "data/%s/%s.properties";

    public static void main(String[] args) throws BiffException, IOException {
//        prepareCats();
//        generateMats(COEF);
//        generateRepairCars(200);
        generateRepairPhones(100);
//        generateCases(300);
        generateCovers(250);
        printHeadsets("headsets");
//        print("headsets");
    }

//    private static void print(String catName) throws IOException {
//        PrintStream out = new PrintStream(new FileOutputStream(String.format(DATA_IMPORT_PATH, catName)));
//        Map<String, String> props = DataHelper.readProps(String.format(PROPERTIES_PATH, catName, catName));
//        printHeader(out);
//        printCategory(props, "cat", out);
//        if (catName.equals("headsets")) {
//            printHeadsets();
//        }
//        printArticles(catName);
//    }

//    private static void printArticles(String catName) throws IOException {
//        String path = String.format(DATA_PATH, catName);
//        File dataFolder = new File(path);
//        File[] brandFiles = dataFolder.listFiles();
//        printHeadsets();
//        for (File brandFile : brandFiles) {
//            if (!brandFile.getName().endsWith(".txt")) {
//                continue;
//            }
//            String[] fields = brandFile.getName().split("\\.");
//            String brandName = fields[1];
//            if (catName.equals("headsets")) {
//                printHeadsets();
//            }
//            System.out.println(brandName);
//        }
//    }

    private static void printHeadsets(Map<String, String> props, String brandName, PrintStream out) throws IOException {
        count = 12000;
        String path = "data/headsets/headsets." + brandName.toLowerCase().replace("sony ericsson", "se") + ".txt";
        BufferedReader reader = new BufferedReader(new FileReader(path));
        String line;
        int num = 0;
//        List<Headset> headsets = new ArrayList<Headset>();
        Map<String, String> templates = new HashMap<String, String>();
        templates.put("\\$\\{brand\\.name\\}", brandName);
        templates.put("\\$\\{url\\}", brandName);
        Map<String, String> filteredProps = filterProps(props, templates);
        printCategory(filteredProps, "headsets.brand", out);
        while ((line = reader.readLine()) != null) {
            if (line.contains("﻿")) {
                line = line.replace("﻿", "");
            }
            Headset headset = Headset.parseHeadset(line, ++num);
            templates.put("\\$\\{headset\\.pin\\}", headset.pin);
            templates.put("\\$\\{headset\\.vendor\\}", headset.vendor);
            templates.put("\\$\\{model\\.type\\}", headset.type);
            filteredProps = filterProps(props, templates);
            printHeadset(filteredProps, headset, out);
        }
    }

    private static void printHeadsets(String catName) throws IOException {
        PrintStream out = new PrintStream(new FileOutputStream(String.format(DATA_IMPORT_PATH, catName)));
        Map<String, String> props = DataHelper.readProps(String.format(PROPERTIES_PATH, catName, catName));
        String path = String.format(DATA_PATH, catName);
        printHeader(out);
        printCategory(props, "cat", out);
        File dataFolder = new File(path);
        File[] brandFiles = dataFolder.listFiles();
        for (File brandFile : brandFiles) {
            if (!brandFile.getName().endsWith(".txt")) {
                continue;
            }
            String[] fields = brandFile.getName().split("\\.");
            String brandName = fields[1];
            List<Headset> headsets = Headset.parseHeadsets(brandName, 2);
//            printHeadsets(props, brandName, out);
            count = 12000;
//            String path = "data/headsets/headsets." + brandName.toLowerCase().replace("sony ericsson", "se") + ".txt";
//            BufferedReader reader = new BufferedReader(new FileReader(path));
//            String line;
//            int num = 0;
//        List<Headset> headsets = new ArrayList<Headset>();
            for (Headset headset : headsets) {
                Map<String, String> templates = new HashMap<String, String>();
                templates.put("\\$\\{brand\\.name\\}", brandName);
                templates.put("\\$\\{art\\.name\\}", headset.name);
                Map<String, String> filteredProps = filterProps(props, templates);
                printCategory(filteredProps, "brandcat", out);
//            while ((line = reader.readLine()) != null) {
//                if (line.contains("﻿")) {
//                    line = line.replace("﻿", "");
//                }
                for (String model : headset.devices) {
                    templates.put("\\$\\{headset\\.pin\\}", headset.pin);
                    templates.put("\\$\\{headset\\.vendor\\}", headset.vendor);
                    templates.put("\\$\\{model\\.type\\}", headset.type);
                    filteredProps = filterProps(props, templates);
                    printHeadset(filteredProps, headset, out);
                }
            }

        }
//        printHeader(out);
//        printCategory(props, "brandcat", out);
//        printHeadsets(props, "Nokia", out);
//        printHeadsets(props, "Samsung", out);
//        printHeadsets(props, "Sony Ericsson", out);
        //To change body of created methods use File | Settings | File Templates.
    }

    private static void printHeader(PrintStream out) {
        header = CSVData.getHeader();
        out.println(header);
    }

    private static void prepareCats() throws BiffException, IOException {
        List<String> categories = new ArrayList<String>();
        List<Repair> cars = ExcelParser.parseRepair(CARS_DATA_FILE, 100);
        for (Repair car : cars) {
            String cat = translateToRus(car.vendor).toUpperCase();
            if (categories.contains(cat)) continue;
            categories.add(cat);
        }
        List<Mat> mats = ExcelParser.parseMatPrice(new File("newxls/ПРАЙС на ПУ ковры салона30.xls"), "", 1);
        for (Mat mat : mats) {
            String cat = translateToRus(mat.category).toUpperCase();
            if (categories.contains(cat)) continue;
            categories.add(cat);
        }
        mats = ExcelParser.parseMatPrice(new File("newxls/ПРАЙС на ПУ поддоны30.xls"), "", 1);
        for (Mat mat : mats) {
            String cat = translateToRus(mat.category).toUpperCase();
            if (categories.contains(cat)) continue;
            categories.add(cat);
        }
        Collections.sort(categories);
        for (String category : categories) {
            checkCatSort(category.toLowerCase());
        }
    }

    private static void generateRepairCars(int price) throws IOException, BiffException {
        Map<String, String> props = DataHelper.readProps("data/cars/remont.properties");
        printCars(props, "data/import/cars-repair-price", price, "cars");
    }

    private static void printCars(Map<String, String> props, String outPath, int price, String prefix) throws IOException, BiffException {
        file_count = 0;
        record_count = 0;
        PrintStream out = new PrintStream(new FileOutputStream(outPath + "_" + file_count++ + ".txt"));
        List<Repair> cars = ExcelParser.parseRepair(CARS_DATA_FILE, price);
        printHeader(out);
        for (Repair car : cars) {
            if (record_count >= 700) {
                record_count = 0;
                out.flush();
                out.close();
                out = new PrintStream(new FileOutputStream(outPath + "_" + file_count++ + ".txt"));
                printHeader(out);
//                printCategory(props, prefix, out);
            }
            Map<String, String> templates = new HashMap<String, String>();
            templates.put("\\$\\{brand\\.name\\}", car.vendor);
            templates.put("\\$\\{brand\\.url\\}", car.vendor);
            templates.put("\\$\\{url\\}", car.vendor);
            Map<String, String> filteredProps = filterProps(props, templates);
            printCategory(filteredProps, "auto", out, true);
            printCategory(filteredProps, "remont", out);
            printPhone(filteredProps, car, out, "remont");
        }
        out.flush();
        out.close();
    }

    private static void generateCovers(int price) throws IOException, BiffException {
        count = 14000;
        record_count = 0;
        Map<String, String> props = DataHelper.readProps("data/phones/cases.properties");
        printPhones(props, "data/import/covers-import.txt", price, "covers");
    }

    private static void generateCases(int price) throws IOException, BiffException {
        count = 16000;
        Map<String, String> props = DataHelper.readProps("data/phones/cases.properties");
        printPhones(props, "data/import/cases-import.txt", price, "cases");
    }

    private static void printPhones(Map<String, String> props, String outPath, int price, String prefix) throws IOException, BiffException {
        PrintStream out = new PrintStream(new FileOutputStream(outPath + "_" + file_count++ + ".txt"));
        List<Repair> phones = ExcelParser.parseRepair("data/phones/phones.xls", price);
        printHeader(out);
        printCategory(props, prefix, out);
        for (Repair phone : phones) {
            if (record_count >= 1100) {
                record_count = 0;
                out.flush();
                out.close();
                out = new PrintStream(new FileOutputStream(outPath + "_" + file_count++ + ".txt"));
                printHeader(out);
                printCategory(props, prefix, out);
            }
            Map<String, String> templates = new HashMap<String, String>();
            templates.put("\\$\\{brand\\.name\\}", phone.vendor);
            templates.put("\\$\\{brand\\.url\\}", phone.vendor);
            templates.put("\\$\\{url\\}", phone.vendor);
            Map<String, String> filteredProps = filterProps(props, templates);
            printCategory(filteredProps, prefix + ".brand", out);
            printPhone(filteredProps, phone, out, prefix);
        }
    }

    private static void printPhone(Map<String, String> props, Repair phone, PrintStream out, String prefix) {
        for (String model : phone.models) {
            record_count++;
            Map<String, String> templates = new HashMap<String, String>();
            templates.put("\\$\\{brand\\.name\\}", phone.vendor);
            templates.put("\\$\\{model\\.name\\}", model);
            templates.put("\\$\\{model\\.url\\}", phone.vendor + "_" + model);
            templates.put("\\$\\{price\\}", phone.price + "");
            Map<String, String> filteredProps = filterProps(props, templates);
            CSVData data = new CSVData();
            data.engname = translateToEng(filteredProps.get(prefix + ".model.engname"));
            data.name = filteredProps.get(prefix + ".model.name");
            data.id = translateToEng(filteredProps.get(prefix + ".model.id"));
            data.desc = filteredProps.get(prefix + ".model.desc");
            data.shortDesc = filteredProps.get(prefix + ".model.shortdesc");
            data.sort = count++ + "";
            data.title = filteredProps.get(prefix + ".model.title");
            data.metaKeywords = filteredProps.get(prefix + ".model.meta.keywords");
            data.metaDesc = filteredProps.get(prefix + ".model.meta.desc");
            data.pics = translateToEng(filteredProps.get(prefix + ".model.photo")).toLowerCase();
            data.price = phone.price + "";
            data.oldPrice = phone.price + "";
            data.count = phone.count + "";
            out.println(data);
        }
    }

    private static Map<String, Integer> catSort = new HashMap<String, Integer>();

    private static void generateRepairPhones(int price) throws BiffException, IOException {
        count = 10000;
        Map<String, String> props = DataHelper.readProps("data/phones/remont.properties");
        printPhones(props, "data/import/phones-repair-price", price, "remont");
    }

    private static void generateMats(double coef) throws BiffException, IOException {
//        header = Helper.readHeaderProps("data/glory/header.properties");
        header = CSVData.getHeader();

        PrintStream out = new PrintStream(new FileOutputStream("data/import/mats-price.txt"));
        System.setOut(out);
        out.println(header);

        Map<String, String> props = DataHelper.readProps("data/glory/mats.properties");
        printMats(props, coef, Type.MATPU);
        printMats(props, coef, Type.BAGMATPU);
    }

//    private static void printRepairPhones(Map<String, String> props, String fileName, int price) throws BiffException, IOException {
//        PrintStream out = new PrintStream(new FileOutputStream(fileName + "_" + file_count++ + ".txt"));
//        List<Repair> phones = ExcelParser.parseRepair("data/phones/phones.xls", price);
//        header = CSVData.getHeader();
//        out.println(header);
//        printCategory(props, "phones", out);
//        for (Repair phone : phones) {
//            if (record_count >= 1100) {
//                record_count = 0;
//                out.flush();
//                out.close();
//                out = new PrintStream(new FileOutputStream(fileName + "_" + file_count++ + ".txt"));
//                header = CSVData.getHeader();
//                out.println(header);
//                printCategory(props, "phones", out);
//            }
//            Map<String, String> templates = new HashMap<String, String>();
//            templates.put("\\$\\{brand\\.name\\}", phone.vendor);
//            templates.put("\\$\\{brand\\.url\\}", phone.vendor);
//            Map<String, String> filteredProps = filterProps(props, templates);
//            printCategory(filteredProps, "phones.brand", out);
//            printPhone(filteredProps, phone, out, "phones");
//        }
//    }

//    private static void printPhone(Map<String, String> props, Repair phone, PrintStream out) {
//        for (String model : phone.models) {
//            record_count++;
//            Map<String, String> templates = new HashMap<String, String>();
//            templates.put("\\$\\{brand\\.name\\}", phone.vendor);
//            templates.put("\\$\\{model\\.name\\}", model);
//            templates.put("\\$\\{model\\.url\\}", phone.vendor + "_" + model);
//            Map<String, String> filteredProps = filterProps(props, templates);
//            CSVData data = new CSVData();
//            data.engname = filteredProps.get("phones.model.engname");
//            data.name = filteredProps.get("phones.model.name");
//            data.id = filteredProps.get("phones.model.id");
//            data.desc = filteredProps.get("phones.model.desc");
//            data.shortDesc = filteredProps.get("phones.model.shortdesc");
//            data.sort = count++ + "";
//            data.title = filteredProps.get("phones.model.title");
//            data.metaKeywords = filteredProps.get("phones.model.meta.keywords");
//            data.metaDesc = filteredProps.get("phones.model.meta.desc");
//            data.picture = filteredProps.get("phones.model.photo");
//            data.price = phone.price + "";
//            data.oldPrice = phone.price + "";
//            data.count = phone.count + "";
//            out.println(data);
//        }
//    }

    private static void printHeadset(Map<String, String> props, Headset headset, PrintStream out) {
        Map<String, String> templates = new HashMap<String, String>();
        templates.put("\\$\\{brand\\.name\\}", headset.brandName);
        templates.put("\\$\\{headset\\.name\\}", headset.brandName + " " + headset.model);
        templates.put("\\$\\{headset\\.url\\}", headset.brandName + "_" + headset.model);
        templates.put("\\$\\{headset\\.type\\}", headset.type);
        templates.put("\\$\\{device\\.reflist\\}", devicesToRef(headset, "Гарнитура", "Headset_"));
        Map<String, String> filteredProps = filterProps(props, templates);
        CSVData data = new CSVData();
        data.engname = filteredProps.get("headset.engname");
        data.name = filteredProps.get("headset.name");
        data.id = filteredProps.get("headset.id");
        data.desc = filteredProps.get("headset.desc");
        data.shortDesc = filteredProps.get("headset.shortdesc");
        data.sort = count++ + "";
        data.title = filteredProps.get("headset.title");
        data.metaKeywords = filteredProps.get("headset.meta.keywords");
        data.metaDesc = filteredProps.get("headset.meta.desc");
        data.pics = filteredProps.get("headset.photo");
        data.price = headset.price + "";
        data.oldPrice = headset.price + "";
        data.count = headset.count + "";
        out.println(data);
        for (String model : headset.devices) {
            templates = new HashMap<String, String>();
            templates.put("\\$\\{brand\\.name\\}", headset.brandName);
            templates.put("\\$\\{headset\\.name\\}", headset.brandName + " " + headset.model);
            templates.put("\\$\\{model\\.name\\}", headset.brandName + " " + model);
            templates.put("\\$\\{model\\.url\\}", headset.brandName + "_" + model);
            filteredProps = filterProps(props, templates);
            data = new CSVData();
            data.engname = filteredProps.get("headset.model.engname");
            data.name = filteredProps.get("headset.model.name");
            data.id = filteredProps.get("headset.model.id");
            data.desc = filteredProps.get("headset.model.desc");
            data.shortDesc = filteredProps.get("headset.model.shortdesc");
            data.sort = count++ + "";
            data.title = filteredProps.get("headset.model.title");
            data.metaKeywords = filteredProps.get("headset.model.meta.keywords");
            data.metaDesc = filteredProps.get("headset.model.meta.desc");
            data.pics = filteredProps.get("headset.model.photo");
            data.price = headset.price + "";
            data.oldPrice = headset.price + "";
            data.count = headset.count + "";
            out.println(data);
        }
    }

//    private static void printHeadset(Map<String, String> props, Headset headset, PrintStream out) {
//        Map<String, String> templates = new HashMap<String, String>();
//        templates.put("\\$\\{brand\\.name\\}", headset.brandName);
//        templates.put("\\$\\{headset\\.name\\}", headset.brandName + " " + headset.model);
//        templates.put("\\$\\{headset\\.url\\}", headset.brandName + "_" + headset.model);
//        templates.put("\\$\\{headset\\.type\\}", headset.type);
//        templates.put("\\$\\{device\\.reflist\\}", devicesToRef(headset, "Гарнитура", "Headset_"));
//        Map<String, String> filteredProps = filterProps(props, templates);
//        CSVData data = new CSVData();
//        data.engname = filteredProps.get("headset.engname");
//        data.name = filteredProps.get("headset.name");
//        data.id = filteredProps.get("headset.id");
//        data.desc = filteredProps.get("headset.desc");
//        data.shortDesc = filteredProps.get("headset.shortdesc");
//        data.sort = count++ + "";
//        data.title = filteredProps.get("headset.title");
//        data.metaKeywords = filteredProps.get("headset.meta.keywords");
//        data.metaDesc = filteredProps.get("headset.meta.desc");
//        data.picture = filteredProps.get("headset.photo");
//        data.price = headset.price + "";
//        data.oldPrice = headset.price + "";
//        data.count = headset.count + "";
//        out.println(data);
//        for (String model : headset.devices) {
//            templates = new HashMap<String, String>();
//            templates.put("\\$\\{brand\\.name\\}", headset.brandName);
//            templates.put("\\$\\{headset\\.name\\}", headset.brandName + " " + headset.model);
//            templates.put("\\$\\{model\\.name\\}", headset.brandName + " " + model);
//            templates.put("\\$\\{model\\.url\\}", headset.brandName + "_" + model);
//            filteredProps = filterProps(props, templates);
//            data = new CSVData();
//            data.engname = filteredProps.get("headset.model.engname");
//            data.name = filteredProps.get("headset.model.name");
//            data.id = filteredProps.get("headset.model.id");
//            data.desc = filteredProps.get("headset.model.desc");
//            data.shortDesc = filteredProps.get("headset.model.shortdesc");
//            data.sort = count++ + "";
//            data.title = filteredProps.get("headset.model.title");
//            data.metaKeywords = filteredProps.get("headset.model.meta.keywords");
//            data.metaDesc = filteredProps.get("headset.model.meta.desc");
//            data.picture = filteredProps.get("headset.model.photo");
//            data.price = headset.price + "";
//            data.oldPrice = headset.price + "";
//            data.count = headset.count + "";
//            out.println(data);
//        }
//    }

    /*
        private static void printCategory(Map<String, String> props, String category, PrintStream out, boolean upper) {
            CSVData data = new CSVData();
            data.engname = translateToEng(props.get(category + ".engname"));
            data.name = upper ? props.get(category + ".name").toUpperCase() : props.get(category + ".name");
            data.name = translateToRus(data.name);
    //        data.name = upper ? props.get(category + ".name").toUpperCase() : props.get(category + ".name");
            checkCatSort(data.name.toUpperCase());
            data.id = translateToEng(props.get(category + ".id"));
            data.desc = translateToRus(props.get(category + ".desc"));
            data.shortDesc = translateToRus(props.get(category + ".shortdesc"));
            data.sort = catSort.get(data.name.toLowerCase()) + "";
            if (data.sort.equals("null")) {
                data.sort = count++ + "";
            }
            data.title = translateToRus(props.get(category + ".title"));
            data.metaKeywords = translateToRus(props.get(category + ".meta.keywords"));
            data.metaDesc = translateToRus(props.get(category + ".meta.desc"));
            data.picture = translateToEng(props.get(category + ".photo")).toLowerCase();
            out.println(data);
        }
    */
    private static void printCategory(Map<String, String> props, String category, PrintStream out, boolean upper) {
        CSVData data = new CSVData();
        data.engname = translateToEng(props.get(category + ".engname"));
        data.name = upper ? props.get(category + ".name").toUpperCase() : props.get(category + ".name");
        data.name = translateToRus(data.name);
        checkCatSort(data.name.toUpperCase());
        data.id = translateToEng(props.get(category + ".id"));
        data.desc = translateToRus(props.get(category + ".desc"));
        data.shortDesc = translateToRus(props.get(category + ".shortdesc"));
        data.sort = catSort.get(data.name.toLowerCase()) + "";
        if (data.sort.equals("null")) {
            data.sort = count++ + "";
        }
        data.title = translateToRus(props.get(category + ".title"));
        data.metaKeywords = translateToRus(props.get(category + ".meta.keywords"));
        data.metaDesc = translateToRus(props.get(category + ".meta.desc"));
//        data.picture = translateToEng(props.get(category + ".photo")).toLowerCase();
        out.println(data);
    }

    private static void printCategory(Map<String, String> props, String category, PrintStream out) {
        printCategory(props, category, out, false);
    }

    public static Map<String, String> filterProps(Map<String, String> props, Map<String, String> templates) {
        return filterProps(props, templates, "");
    }

    public static String filterProp(String prop, String template, String value) {
        if (prop == null) {
            return "";
        }
        String filteredProp = prop.replaceAll(template, value);
        if (template.contains("url")) {
            filteredProp = DataHelper.codeInURL(filteredProp);
        }
        return filteredProp;
    }

    public static Map<String, String> filterProps(Map<String, String> props, Map<String, String> templates, String propsName) {
        Map<String, String> filteredProps = new HashMap<String, String>();
        for (String key : props.keySet()) {
            if (!key.startsWith(propsName)) {
                continue;
            }
            String value = props.get(key);
            for (String filterKey : templates.keySet()) {
                String filterKeyValue = templates.get(filterKey);
//                if (filterKeyValue.contains("#{") || filterKeyValue.contains("${")) {
//                    System.out.println("filterKeyValue = " + filterKeyValue);
//                    System.out.println("value = " + value);
//                }
                if (filterKey.contains("url")) {
                    value = value.replaceAll(filterKey, DataHelper.codeInURL(filterKeyValue).trim()).trim();
                } else {
                    value = value.replaceAll(filterKey, filterKeyValue).trim();
                }
                if (key.contains("photo")) {
                    value = value.toLowerCase();
                }
            }
            filteredProps.put(key, value);
        }
        return filteredProps;
    }


    private static void printMats(Map<String, String> props, double coef, Type type) throws IOException, BiffException {
        File priceFile = null;
        if (type.equals(Type.MATPU)) {
            priceFile = new File("newxls/ПРАЙС на ПУ ковры салона30.xls");
        } else if (type.equals(Type.BAGMATPU)) {
            priceFile = new File("newxls/ПРАЙС на ПУ поддоны30.xls");
        }
        List<Mat> mats = ExcelParser.parseMatPrice(priceFile, "", coef);
        Map<String, List<Mat>> matsByCategory = DataHelper.splitByCategory(mats);
        ArrayList<Comparable> categories = new ArrayList<Comparable>(matsByCategory.keySet());
        Collections.sort(categories);
        for (Comparable category : categories) {
            count++;
            String cat = processName(((String) category).toLowerCase());
            Map<String, String> templates = new HashMap<String, String>();
            templates.put("\\$\\{brand\\.name\\}", (String) category);
            templates.put("\\$\\{brand\\.url\\}", (String) category);
            templates.put("\\$\\{url\\}", (String) category);
            Map<String, String> filteredProps = filterProps(DataHelper.readProps("data/cars/remont.properties"), templates);
            printCategory(filteredProps, "auto", System.out, true);
//            checkCatSort(cat.toUpperCase());
//            data.sort = catSort.get(cat) + "";
//            data.name = cat.toUpperCase();
//            data.engname = cat.toUpperCase();
//            data.id = cat.toLowerCase();
//            data.picture = cat.toLowerCase() + ".jpg";
            printMatCategory(props, type, cat, System.out);
            List<Mat> matsByCat = matsByCategory.get(category);
            for (Mat mat : matsByCat) {
                CSVData data = new CSVData();
                Matcher m = p.matcher(mat.model);
                String model = mat.model;
                if (m.find()) {
                    model = mat.model.substring(0, m.start());
                }
                if (type.equals(Type.MATPU)) {
                    data.name = translateToRus("Коврик в салон " + mat.model);
                    data.engname = translateToEng("Auto mat for " + mat.model);
                    data.id = filterURL(props.get("matpu.model.id"), translateToEng(mat.model));
                    data.pics = "mat-medium.jpg,mat-small.jpg,mat-large.jpg";
                } else if (type.equals(Type.BAGMATPU)) {
                    data.name = translateToRus("Коврик в багажник " + mat.model);
                    data.engname = translateToEng("Auto bag mat for " + mat.model);
                    data.id = filterURL(props.get("bagmatpu.model.id"), translateToEng(mat.model));
                    data.pics = "bagmat-medium.jpg,bagmat-small.jpg,bagmat-large.jpg";
                }
                data.desc = translateToRus(props.get(type.toString().toLowerCase() + ".model.desc").replace("${model}", mat.model));
                data.shortDesc = translateToRus(props.get(type.toString().toLowerCase() + ".model.shortdesc").replace("${model}", mat.model));
                data.title = translateToRus(props.get(type.toString().toLowerCase() + ".model.title").replace("${model}", mat.model).replace("${model.translit}", translitVendor(model)));
                data.metaDesc = translateToRus(props.get(type.toString().toLowerCase() + ".model.title").replace("${model}", cat).replace("${model.translit}", translitVendor(model)));
                data.metaKeywords = translateToRus(props.get(type.toString().toLowerCase() + ".model.title").replace("${model}", cat).replace("${model.price}", mat.price + "").replace("${model.translit}", translitVendor(model)));
                data.price = mat.price + "";
                data.sort = count++ + "";
                data.count = "100";
                System.out.println(data);
            }
        }
        String fileName;
        String prefix;
        file_count = 0;
        record_count = 0;
        if (type.equals(Type.MATPU)) {
            fileName = "data/import/vel-mat-price" + "_" + file_count++ + ".txt";
            prefix = "matvel";
        } else {
            fileName = "data/import/vel-bagmat-price" + "_" + file_count++ + ".txt";
            prefix = "bagmatvel";
        }
        PrintStream out = new PrintStream(new FileOutputStream(fileName));
        List<Repair> cars = ExcelParser.parseRepair(CARS_DATA_FILE, 2200);
        printHeader(out);
        for (Repair car : cars) {
            record_count++;
            if (record_count >= 700) {
                record_count = 0;
                out.flush();
                out.close();
                if (type.equals(Type.MATPU)) {
                    fileName = "data/import/vel-mat-price" + "_" + file_count++ + ".txt";
                } else {
                    fileName = "data/import/vel-bagmat-price" + "_" + file_count++ + ".txt";
                }
                out = new PrintStream(new FileOutputStream(fileName));
                printHeader(out);
            }
            printAutoCategory(out, car);
            printMatCategory(props, type, car.vendor, out);
            printPhone(props, car, out, prefix);
        }
        out.flush();
        out.close();
    }

    private static void printAutoCategory(PrintStream out, Repair car) throws IOException {
        Map<String, String> templates = new HashMap<String, String>();
        templates.put("\\$\\{brand\\.name\\}", car.vendor);
        templates.put("\\$\\{brand\\.url\\}", car.vendor);
        templates.put("\\$\\{url\\}", car.vendor);
        Map<String, String> filteredProps = filterProps(DataHelper.readProps("data/cars/remont.properties"), templates);
        printCategory(filteredProps, "auto", out, true);
    }

    private static CSVData printMatCategory(Map<String, String> props, Type type, String cat, PrintStream out) {
        CSVData data = new CSVData();
        String typeString;
        if (type.equals(Type.MATPU)) {
            typeString = "в салон";
            data.id = translateToEng(props.get("mat.id").replace("${type.url}", "kovrik_v_salon").replace("${vendor.url}", cat.toLowerCase()));
            data.engname = translateToEng(props.get("mat.engname").replace("${type}", "v salon").replace("${vendor}", cat.toUpperCase()));
        } else {
            typeString = "в багажник";
            data.id = translateToEng(props.get("mat.id").replace("${type.url}", "kovrik_v_bagazhnik").replace("${vendor.url}", cat.toLowerCase()));
            data.engname = translateToEng(props.get("mat.engname").replace("${type}", "v bagazhnik").replace("${vendor}", cat.toUpperCase()));
        }
        data.name = translateToRus(props.get("mat.name").replace("${type}", typeString).replace("${vendor}", cat.toUpperCase()));
        data.desc = translateToRus(props.get("mat.desc").replace("${type}", typeString).replace("${vendor}", cat));
        data.metaDesc = translateToRus(props.get("mat.metadesc").replace("${vendor}", cat).replace("${type}", typeString));
        data.metaKeywords = translateToRus(props.get("mat.metakey").replace("${vendor}", cat).replace("${type}", typeString));
        data.title = translateToRus(props.get("mat.title").replace("${type}", typeString).replace("${vendor}", cat));
        data.sort = count++ + "";
        out.println(data);
        return data;
    }

    private static String processName(String name) {
        if (name.contains("универсальные")) {
            name = "Универсальные";
        }
        if (name.contains("vaz")) {
            name = "ваз";
        }
        if (name.contains("tagaz")) {
            name = "тагаз";
        }
        return name;
    }

    private static void checkCatSort(String cat) {
        if (!catSort.containsKey(cat)) {
            catSort.put(cat, count++);
        }
    }

    public static String replaceVendor(String name, String vendor, boolean isTranslit) {
        return isTranslit ? name.replace("${vendor}", vendor) : name.replace("${vendor.translitUrl}", translitVendor(vendor));
    }

    public static String translitVendor(String name) {
        if (name.equalsIgnoreCase("chevrolet")) {
            name = "Шевроле";
        }
        if (name.equalsIgnoreCase("brilliance")) {
            name = "Брилианс";
        }
        return Helper.translit(name);
    }

    private static String filterURL(String url, String name) {
        url = url.replace("${url}", DataHelper.codeInURL(name));
        url = url.replace("${model.url}", DataHelper.codeInURL(name));
        url = url.replaceAll("\\\\", "-");
        url = url.replaceAll("\\/", "-");
        url = url.replaceAll("\\.", "");
        url = url.replaceAll("\\,", "");
        url = translateToEng(url);
        return url;
    }

    public static String translateToEng(String name) {
        if (name == null) {
            return null;
        }
        name = name.replace("зад", "zad");
        name = name.replace("пер", "per");
        name = name.replace("3-х", "3-h");
        name = name.replace("3-й", "3-y");
        name = name.replace("местный", "mestnyi");
        name = name.replace("мест", "mest");
        name = name.replace("ряд", "ryad");
        name = name.toLowerCase().replace("ваз", "vaz");
        name = name.toLowerCase().replace("москвич", "moscvic");
        name = name.toLowerCase().replace("азлк", "AZLK");
        name = name.toLowerCase().replace("уаз", "uaz");
        name = name.toLowerCase().replace("дуэт", "duet");
        name = name.toLowerCase().replace("калита", "kalita");
        name = name.toLowerCase().replace("князь", "knyz");
        name = name.toLowerCase().replace("владимир", "vladimir");
        name = name.toLowerCase().replace("святогор", "svyatogor");
        name = name.toLowerCase().replace("юрий", "yury");
        name = name.toLowerCase().replace("долгорукий", "dolgorukiy");
        name = name.toLowerCase().replace("газ", "gaz");
        name = name.toLowerCase().replace("иж", "izh");
        name = name.toLowerCase().replace("надежда", "nadezhda");
        name = name.toLowerCase().replace("ока", "oka");
        name = name.toLowerCase().replace("универсал", "universal");
        name = name.toLowerCase().replace("седан", "sedan");
        name = name.toLowerCase().replace("хэтчбек", "hatchback");
        name = name.toLowerCase().replace("заз", "zaz");
        name = name.toLowerCase().replace("тагаз", "tagaz");

        name = name.toLowerCase().replace("нива", "Niva");
        name = name.toLowerCase().replace("лада", "Lada");
        name = name.toLowerCase().replace("калина", "Kalina");
        name = name.toLowerCase().replace("приора", "Priora");
        name = name.toLowerCase().replace("ока", "Oka");
        name = name.toLowerCase().replace("хантер", "Hunter");
        name = name.toLowerCase().replace("патриот", "Patriot");
        name = name.toLowerCase().replace("орбита", "Orbita");
        name = name.toLowerCase().replace("славута", "Slavuta");
        name = name.toLowerCase().replace("таврия", "Tavria");
        name = name.toLowerCase().replace("люкс", "lux");
        name = name.toLowerCase().replace("ваз", "VAZ");
        name = name.toLowerCase().replace("уаз", "UAZ");
        name = name.toLowerCase().replace("волга", "volga");
        name = name.toLowerCase().replace("эконом", "econom");
        return name;
    }

    public static String translateToRus(String name) {
        if (name == null) {
            return null;
        }
        name = name.replace("VAZ", "ВАЗ");
        name = name.replace("ZAZ", "ЗАЗ");
        name = name.replace("AZLK", "МОСКВИЧ (АЗЛК)");
        name = name.replace("GAZ", "ГАЗ");
        name = name.replace("gaz", "ГАЗ");
        name = name.replace("IZH", "ИЖ");
        name = name.replace("TAGAZ", "ТАГАЗ");
        name = name.replace("UAZ", "УАЗ");
        name = name.replace("IZH", "ИЖ");

        name = name.replace("Patriot", "Патриот");
        name = name.replace("Siber", "Сайбер");
        name = name.replace("Volga", "Волга");
        name = name.replace("Sens", "Сенс");
        return name;
    }

    private static String devicesToRef(Headset headset, String name, String urlPrefix) {
        if (headset.devices.length > 10) {
            return devicesToTableRef(headset, name, 4, urlPrefix);
        }
        StringBuilder sb = new StringBuilder("<ul>");
        for (String device : headset.devices) {
            String deviceName = name + " " + headset.brandName + " " + device;
            String deviceUrl = DataHelper.codeInURL(headset.brandName) + "_" + DataHelper.codeInURL(device);
            if (deviceUrl.equals(DataHelper.codeInURL(headset.model))) continue;
            sb.append("<li><strong><a href=\"http://extramobi.ru/").append("product/").append(urlPrefix).append(deviceUrl).append("\">").append(deviceName).append("</a></strong></li>");
        }
        sb.append("</ul><br/>");
        return sb.toString();
    }

    public static String devicesToTableRef(Headset headset, String name, int columns, String urlPrefix) {
        StringBuilder sb = new StringBuilder("<table style=\"font-size:13px\">");
        for (int i = 1; i <= headset.devices.length; i++) {
            if (i == 1 && i % columns + 1 == 0) {
                sb.append("<tr>");
            }
            String device = headset.devices[i - 1];
            String deviceName = name + " " + headset.brandName + " " + device;
            String deviceUrl = DataHelper.codeInURL(headset.brandName) + "_" + DataHelper.codeInURL(device);
//            sb.append("<td width=\"150\"><strong>").append(name).append(" ").append(models[i - 1]).append("</strong></td>");
            sb.append("<td width=\"200\"><strong><a href=\"http://extramobi.ru/").append("product/").append(urlPrefix).append(deviceUrl).append("\">").append(deviceName).append("</a></strong></td>");

            if (i % columns == 0) {
                sb.append("</tr>");
            }
        }
        if (sb.toString().endsWith("</td>")) {
            sb.append("</tr>");
        }
        sb.append("</table>");
        return sb.toString();
    }


}

enum Type {
    MATPU, BAGMATPU;
}
